package org.bendev.ildaplayer;

import java.util.Calendar;
import java.util.TimeZone;

import android.text.format.Time;

public abstract class DateUtils {
	public static Calendar date( Calendar c ){
		Calendar res = (Calendar) c.clone();
		res.set( Calendar.HOUR_OF_DAY, 0 );
		res.set( Calendar.MINUTE, 0 );
		res.set( Calendar.SECOND, 0 );
		res.set( Calendar.MILLISECOND, 0 );
		return res;
	}
	
	public static Calendar date( int year, int month, int day ){
		Calendar res = Calendar.getInstance();
		res.set( year, month, day );
		return date( res );
	}
	
	public static Calendar week( Calendar c ){
		Calendar res = (Calendar) c.clone();
		res.add( Calendar.DATE, -((5+res.get( Calendar.DAY_OF_WEEK ))%7) );
		return res;
	}
	
	public static Calendar add( Calendar c, int field, int value ){
		Calendar res = (Calendar) c.clone();
		res.add( field, value );
		return res;
	}
	
	public static Calendar add( Calendar c, long dt ){
		Calendar res = (Calendar) c.clone();
		res.setTimeInMillis( res.getTimeInMillis() + dt );
		return res;
	}
	
	public static Calendar round( Calendar c, long t ){
		Calendar res = (Calendar) c.clone();
		res.setTimeInMillis( ( ( res.getTimeInMillis() + t/2 ) / t ) * t );
		return res;
	}

	public static String iso( Calendar c ){
		Time t = new Time( Time.TIMEZONE_UTC );
		t.set( c.getTimeInMillis() );
		return t.format3339( false );
	}

	public static Calendar iso( String str ){
		Time t = new Time( Time.TIMEZONE_UTC );
		t.parse3339( str );
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis( t.toMillis( false ) );
		return c;
	}

	public static Calendar local( Calendar c ){
		Calendar res = Calendar.getInstance();
		res.setTime( c.getTime() );
		return res;
	}
	
	public static Calendar gmt( Calendar c ){
		Calendar res = Calendar.getInstance( TimeZone.getTimeZone( "GMT" ) );
		res.setTime( c.getTime() );
		return res;
	}
}
